<?php

namespace backend\controllers;

use app\models\RoleTask;
use app\models\Task;
use common\core\ZController;
use Yii;
use app\models\Role;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\ConflictHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * RoleController implements the CRUD actions for Role model.
 */
class RoleController extends ZController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Role models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Role::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Role model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Role model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Role();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->role_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Role model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->role_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Role model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Role model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Role the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Role::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionGive()
    {
        $rid = intval(Yii::$app->request->get('rid'));
        if ($rid == 0) {
            throw new ConflictHttpException('参数错误');
        }
        $roleModel = $this->findModel($rid);
        if (!$roleModel) {
            throw new ConflictHttpException('无法找到此角色');
        }

        $task = new Task();
        $tasks = [];
        $tasks = $task->getAllTaskToArray();
        $exists = [];
        return $this->render('give', [
            'tasks' => $tasks,
            'exists' => $exists,
            'role_id' => $rid,
        ]);
    }

    public function actionAssign($action)
    {
        $post = \Yii::$app->getRequest()->post();
        $rid = $post['role_id'];

        if (!$rid) {
            echo ['error' => 1, 'msg' => '参数错误'];
            \Yii::$app->end();
        }

        $tasks = $post['tasks'];
        $error = [];

        if ($action == 'assign') {

            $this->saveRoleTask($rid, $tasks);

        } else if ($action == 'delete') {

            foreach ($tasks as $task_id) {
//                $roleTaskModel->task_id = $task_id;
//                $roleTask = $roleTaskModel->getRoleTaskByBothId();
                $roleTaskModel = RoleTask::findOne(['task_id' => $task_id,'role_id' => $rid]);

                if (!$roleTaskModel) {
                    continue;
                }
                try {

                    $roleTaskModel->delete();

                } catch (Exception $exc) {
                    $error[] = $exc->getMessage();
                }
            }
        } else {
            echo ['error' => 2, 'msg' => '请求类型不存在'];
            \Yii::$app->end();
        }
        \Yii::$app->getResponse()->format = Response::FORMAT_JSON;
        $result = [];
        $result = $this->renderForSelect($rid);
        return [$result[0],
            $result[1], $error];
    }

    public function saveRoleTask($role_id, $tasks)
    {
        if (empty($tasks)) {
            return;
        }
        $roleTaskModel = new RoleTask();
        foreach ($tasks as $task) {
            //先查询此记录是否存在，存在就继续循环
            $taskItem = $roleTaskModel->findOne(['role_id' => $role_id, 'task_id' => $task]);
            if ($taskItem) {
                continue;
            }
            $roleTaskModel->isNewRecord = true;
            $roleTaskModel->role_id = $role_id;
            $roleTaskModel->task_id = $task;
            if (!$roleTaskModel->save()) {
                var_dump($roleTaskModel->getErrors());die;
                Yii::error(Json::encode($roleTaskModel->getErrors()));
                return false;
            }
        }
    }


    public function renderForSelect($role_id)
    {

        $result = [];

        $existsOptions = [];
        $roleTaskModel = new RoleTask();
        $roleTaskModel->role_id = $role_id;
        //已经存在的授权任务id
//        $exists = $roleTaskModel->find()->select(['task_id'])->asArray()->all();
        $exists = $roleTaskModel->getAllTasksByRoleId();
//        var_dump($exists);die;
        //获取所有的授权任务
        $taskModel = new Task();
        $tasks = $taskModel->getAllTaskToArray();
//        var_dump($tasks);die;
        foreach ($tasks as $key => $task) {

            if (array_key_exists($key, $exists)) {
                continue;
            }

            $result[$key] = $task;
        }

        $arr = [
            Html::renderSelectOptions('', $result),
            Html::renderSelectOptions('', $exists),
        ];
        return $arr;
    }
}
